const WORKOUT_KEY = 'workout_plans'

export const workoutService = {
  getPlans() {
    try {
      if (typeof window === 'undefined') return []
      const plans = localStorage.getItem(WORKOUT_KEY)
      return plans ? JSON.parse(plans) : []
    } catch (error) {
      console.error('获取计划失败:', error)
      return []
    }
  },

  savePlan(plan) {
    try {
      const plans = this.getPlans()
      const newPlan = {
        ...plan,
        id: plan.id || Date.now().toString(),
        days: Array.isArray(plan.days) ? plan.days : [],
        exercises: Array.isArray(plan.exercises) ? plan.exercises : [],
        type: plan.type || '常规训练'
      }
      
      const index = plans.findIndex(p => p.id === newPlan.id)
      if (index > -1) {
        plans[index] = newPlan
      } else {
        plans.push(newPlan)
      }
      
      localStorage.setItem(WORKOUT_KEY, JSON.stringify(plans))
      return newPlan
    } catch (error) {
      console.error('保存计划失败:', error)
      throw error
    }
  },

  deletePlan(planId) {
    try {
      const plans = this.getPlans().filter(plan => plan.id !== planId)
      localStorage.setItem(WORKOUT_KEY, JSON.stringify(plans))
    } catch (error) {
      console.error('删除计划失败:', error)
      throw error
    }
  }
}